package com.focusthings.pro.xianxiabao.order.order.api;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.focusthings.common.service.mall.item.item.service.IMallItemItemService;
import com.focusthings.common.service.mall.pay.order.entity.MallPayOrder;
import com.focusthings.common.service.mall.pay.order.service.IMallPayOrderService;
import com.focusthings.common.service.mall.pay.pay.bytedance.ByteDancePayService;
import com.focusthings.common.service.mall.pay.pay.bytedance.CheckInfo;
import com.focusthings.common.service.mall.pay.util.HttpRequestUtil;
import com.focusthings.common.service.notify.email.config.Email;
import com.focusthings.common.service.notify.email.util.EmailUtil;
import com.focusthings.pro.songlibao.item.item.entity.ProSonglibaoItemDouyin;
import com.focusthings.pro.songlibao.item.item.service.IProSonglibaoItemDouyinService;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
* @Description: 支付
* @Author: jeecg-boot
* @Date:   2020-12-29
* @Version: V1.0
*/
@Api(tags="服务-商城-支付-biz-字节平台-个人支付-微信/支付宝-api")
@RestController
@RequestMapping("/pay/pay/bytedance/per/api")
@Slf4j
public class ByteDancePayControllerApi extends JeecgController<MallPayOrder, IMallPayOrderService> {
   @Autowired
   private IMallPayOrderService mallPayOrderService;
   @Autowired
   private ByteDancePayService byteDancePayService;
   @Autowired
   private IProSonglibaoItemDouyinService iProSonglibaoItemDouyinService;

   @Autowired
   private IMallItemItemService iMallItemItemService;


   /**
    * 支付
    * @param mallPayOrder
    * @return
    */
   @AutoLog(value = "服务-商城-支付-biz-微信支付-个人-支付")
   @ApiOperation(value="服务-商城-支付-biz-微信支付-个人-支付", notes="服务-商城-支付-biz-微信支付-个人-支付")
   @GetMapping(value = "/pay")
   @Transactional(rollbackFor = Exception.class)
   public Result<?> createOrder(MallPayOrder mallPayOrder) {

      mallPayOrder.setOrderId(IdUtil.simpleUUID());

      //生成订单
      mallPayOrderService.save(mallPayOrder);
       try {
          //下单返回签名
          Map<String, Object> returnSign =byteDancePayService.byteDancePay(mallPayOrder);
          //更新预下单订单
          mallPayOrder.setStatus(1);
          mallPayOrderService.saveOrUpdate(mallPayOrder);
          if(returnSign==null){
             return Result.error("返回错误");
          }
          return Result.OK(new JSONObject(returnSign));
       } catch (Exception e) {
          e.printStackTrace();
          return Result.error(e.getMessage());
       }

   }

   @Autowired
   private EmailUtil emailUtil;

   /**
    * 支付通知
    * @return
    * @throws IOException
    */
   @AutoLog(value = "服务-商城-支付-biz-微信支付-个人-支付通知")
   @ApiOperation(value="服务-商城-支付-biz-微信支付-个人-支付通知", notes="服务-商城-支付-biz-微信支付-个人-支付通知")
   @PostMapping(value = "/notify")
   @Transactional(rollbackFor = Exception.class)
   public String notify(HttpServletRequest httpServletRequest) throws IOException, WxPayException {

      String jsonR = IOUtils.toString(httpServletRequest.getInputStream(), httpServletRequest.getCharacterEncoding());
//      log.info("byteDancePay.notify.jsonR:{}",jsonR);
      CheckInfo checkInfo = JSONObject.parseObject(jsonR,CheckInfo.class);
      log.debug("byteDancePay.notify.checkInfo:{}",checkInfo);

      HashMap paramMap = new HashMap();
      paramMap.put("appid","ttcbe5bd5854dd728601");
      paramMap.put("secret","02a5ba23866c40bdf4f5606ee593c8798c20f48e");
      paramMap.put("grant_type","client_credential");
      String jsonStr = HttpRequestUtil.sendPost("https://developer.toutiao.com/api/apps/v2/token",new  JSONObject(paramMap).toJSONString());
      JSONObject rs = JSONObject.parseObject(jsonStr);
      if(rs==null){
         log.error("没有拿到token:B");
         return "error";
      }
      if(rs!=null && !rs.getString("err_no").equals("0")){
         log.error("没有拿到token:ByteDancePayController.notify.token,postPrams.msg:{}",checkInfo.getMsg());
         return "error";
      }
      String access_token = rs.getJSONObject("data").getString("access_token");
      String expires_in =  rs.getJSONObject("data").getString("expires_in");
      String[] sign= new String[]{access_token,checkInfo.getTimestamp().toString(),checkInfo.getNonce(),checkInfo.getMsg()};
      Arrays.sort(sign);
      String hash = DigestUtils.sha1Hex(StringUtils.join(sign, ""));
      if(!hash.equals(checkInfo.getMsg_signature())) {
         QueryWrapper queryWrapper = new QueryWrapper();
         JSONObject msgRs = JSONObject.parseObject(checkInfo.getMsg());
         if(msgRs.getString("status").equals("SUCCESS")){
            queryWrapper.eq("order_id", msgRs.getString("payment_order_no"));
            MallPayOrder mallPayOrder = mallPayOrderService.getOne(queryWrapper);
            // 处理订单
            if(mallPayOrder==null){return "error";}
            Integer payStatus = mallPayOrder.getStatus();
            if (payStatus != 1 || payStatus != 2) {
               UpdateWrapper uw = new UpdateWrapper();
               uw.set("status", 1);
               uw.set("cps",checkInfo.getMsg());
               uw.eq("order_id", mallPayOrder.getOrderId());
               Boolean isUpdate = mallPayOrderService.update(uw);
               if (isUpdate) {
                  Email email = new Email("283641971@qq.com", "字节支付-送礼宝-支付回调完成通知："+checkInfo.getMsg(),
                          "字节支付-送礼宝订单通知：" +
                                  "<div style='text-indent:2em'>"+JSONObject.toJSONString(mallPayOrder)+"</div>");
                  emailUtil.sendEmail(email);

//                  JSONObject params = new  JSONObject();
//                  params.put("access_token",access_token);
//                  params.put("app_id","tt3bf14d4ca4c9829301");
//                  params.put("tpl_id","MSG1184996ccaf41b2d0804741b24ab308acc79eeb13929");
//                  params.put("open_id",mallPayOrder.getPin());
//
//                  JSONObject dataJ = new JSONObject();
//                  dataJ.put("订单号",mallPayOrder.getOrderId());
//                  dataJ.put("查询内容","您在字节跳动-抖音的支付完成");
//                  dataJ.put("查询状态","支付成功");
//                  params.put("data",dataJ);
//
//                  HttpRequestUtil.sendPost("https://developer.toutiao.com/api/apps/subscribe_notification/developer/v1/notify",params.toJSONString());

                  return "{\n" +
                          "  \"err_no\": 0,\n" +
                          "  \"err_tips\": \"success\"\n" +
                          "}";
               } else {
                  return "{\n" +
                          "  \"err_no\": 1,\n" +
                          "  \"err_tips\": \"success\"\n" +
                          "}";
               }
            } else {
               return "{\n" +
                       "  \"err_no\": 1,\n" +
                       "  \"err_tips\": \"success\"\n" +
                       "}";
            }
         }else{
            return "{\n" +
                    "  \"err_no\": 1,\n" +
                    "  \"err_tips\": \"success\"\n" +
                    "}";
         }
      }else{
         return "{\n" +
                 "  \"err_no\": 1,\n" +
                 "  \"err_tips\": \"success\"\n" +
                 "}";
      }
      }
}
